import requests
import json
import datetime
from utils.config import http_config,login_list,max_length
from requests_toolbelt.multipart import encoder
import random
now = datetime.datetime.now()
now_time = now.strftime("%Y-%m-%d %H:%M:%S")

def get_pwd(phone):
	match = [user for user in login_list if user["phone"] == phone]
	if(len(match) ==0):
		print("获取密码失败")
		
	else:
		print(f"当前身份:{match[0]['role']}")
		return match[0]['pwd']


def get_token(phone):
	url = http_config['baseUrl'] +	"/user/login"
	payload = {
		"phone":phone,
		"pwd":get_pwd(phone)
	}
	res = requests.post(url,json=payload)
	# print(res.text)
	
	res_json = json.loads(res.text)
	if(res_json['code']==200):
		return res_json['data']['token']
	else:
		print(res_json)
	# print(res.text)

def rsa_decode(encoded_data):

	pem_private_key = '-----BEGIN RSA PRIVATE KEY-----\n' + 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCXPh19eZR9X9S9gsN0S/uQqCmgjtZmH45+NEldmCTnolUBrW/qtIg3pYSSYrtJgwijjYI0sWbcxcyG61vdeRsaEAofhxYiIa1f899qfWG9p90EZdClm/Lrm3O7kBb5SV8Rb03IUyp5tUzacWs/0K2XEi+V9fRrmHZ4vi/jMs3I4VunIYtO+K9BGIiMF9N1+XVI7bahrOYmPJFf0vL07iWugFH7RUhjIOGWE+5jwcUvcOl6Y1fSOXVUmSoFLbuIC8DIYP3PxshXwFGFoKnKAq9m66nP/eQronATeRqEGs1n9VSszAGc+zFwDa+1JCOCAHqofU5CoYAKYcGqmBViJPuZAgMBAAECggEAOPd3iiR6TsMC0aLoVeysw67jhwtmLC8kr9qn66378JePZ0NZjVEUockhZzXzD1xgq6IIciqD8RI72HHcN05/a9Cwz3FFX/PJZwPnmifB4frRX++tqENWO3JhJDvAu4LsYRfId3UD4bXtTbY8zFuglu+NpvFub/yMWyxfwzcGleveuKY12mFD54ks0zg6Lvz9hgf3+SAb9OVXSF7/i17LpmT0IO/WkM0ELA2fD43ztdeGPWJDATN7tryJZWYbkamFb12LK2XNTChgDrU3+NrY1M8MIa27E0R0UOs3ic5Qx3zCmwvwRVM8wCsNzg6sX9Y8DHAmevJk0++bKtN7jUlJJQKBgQDiRbA2+M6n3dmEtI4RhJZdWZKmzatiMSh8Qv9pQi9/uP7jxuCHMLTXqtEjjoes3YPiXcKE8vOcV9JmrZYNvpTFt6DL2l2sTxm66HZo96AXvD7cfXu1XesWF4ManpJOaCiWInVPu0KciPWeOqi5/okaRcIMla5yjLzjW6A3cQEFZwKBgQCrHOykUcayFKK5qrSFpUZh1g55cSwt9rQcRXdP+KO3Js/Wc6euiJNVYBFioGiyszCiIjErRv7HPaxo6RvH4ch2Snlg8Dm9TFKgCj2roOs9WiM8V9nRSpAvkHah9XbMM1YfpJoXLgCdlClrLv/XVWoKf8m8Hv867oDm3sLecTBW/wKBgCcOQEw8xe7TrCfrwlnjuNCEFXwVI+/e7E4Ggm94rRoupFBMk5TCI3TWVyL8Bw8fbRQ1es3X4ZSq0/ZFIBFfQ+6cs3R8TI7hWF+aoFWd6FQweek0/5VekKVPiaGenUJLWDYR3I3WlLjQKxUUqurvtFqEj+n8LBA5mqDjv9PR/YshAoGADErTpSpKv9hDqFrfBQrOd5DNEWRT7Clg3vcOjywpdqrPG3TLgvpEu0lfdlpXqx68S6lxJs6+1slTbWXxnPZXVEgdWB1pyHOHLAAQVhgFTi7/gQI+n45ftUsHerMLibfWZAeLGkcvvCI8p3qE3o9AQujTMTR42V7w26T9EsXG1zkCgYBClZbLD19fdcbYfGm58vi7pNGZujw1rWmWip1472p4JuZBzGKuwg7JjEh/T2Zcc6D6Eiy4f+8AZEUSISda5ZGJt+WkThwlPOfovycso23tzCBDm4WdYXf/gXjFnGSkWBUTXAbx0UniAG/VbsN9g/YpV4T1MPFQE6zH4O0H44w3Aw==\n'+ '-----END RSA PRIVATE KEY-----'

	private_key = RSA.import_key(pem_private_key)

	try:
		cipher_rsa = PKCS1_OAEP.new(private_key)
		decrypted_data = cipher_rsa.decrypt(encoded_data)
		print("Decrypted data:", decrypted_data)
	except (ValueError, TypeError) as e:
		print("Decryption failed:", e)


def opo_post(url,payload,token):
	res_url = http_config['baseUrl'] + url
	headers = {
		"token":token
	}
	res = requests.post(res_url,json=payload,headers=headers)
	res_json = json.loads(res.text)
	if(len(res.text) > max_length):
		print(f'{now_time} {url} {res.text[:max_length]}......')
	else:
		print(f'{now_time} {url} {res_json}')
	return res_json

def opo_get(url,params,token):

	res_url = http_config['baseUrl'] + url
	headers = {
		"token":token
	}
	res = requests.get(res_url,params=params,headers=headers)
	res_json = json.loads(res.text)
	if(len(res.text) > max_length):
		print(f'{now_time} {url} {res.text[:max_length]}......')
	else:
		print(f'{now_time} {url} {res_json}')
	return res_json

def opo_upload(url,params,token):
	res_url = http_config['baseUrl'] + url
	headers = {
		"token":token
	}
	file_path = 'static/flow-test.png'
	files = {'file': open(file_path, 'rb')} 
	res = requests.post(res_url,params=params,headers=headers,files=files)
	# 注意: post请求带了params
	res_json = json.loads(res.text)
	if(len(res.text) > max_length):
		print(f'{now_time} {url} {res.text[:max_length]}......')
	else:
		print(f'{now_time} {url} {res_json}')
	return res_json

def opo_mix_upload(url,payload,token):
	res_url = http_config['baseUrl'] + url
	json_str = json.dumps(payload)
	file_path = 'static/flow-test.png' 
	m = encoder.MultipartEncoder(
		fields=[
			('supplement_info', ('blob', json_str.encode('utf-8'), 'application/json'))
		]
	)
	headers = {
	'Content-Type': m.content_type,
	"token":token
	}
	res = requests.post(res_url, data=m.to_string(), headers=headers)
	res_json = json.loads(res.text)
	if(len(res.text) > max_length):
		print(f'{now_time} {url} {res.text[:max_length]}......')
	else:
		print(f'{now_time} {url} {res_json}')
	return res_json


def opo_mix_upload_step7(url,payload,token):
	res_url = http_config['baseUrl'] + url
	json_str = json.dumps(payload)
	file_path = 'static/flow-test.png' 
	m = encoder.MultipartEncoder(
		fields=[
			('id_cards', ('flow-test.png', open(file_path, 'rb'), 'image/png')),
			('donation_registration_form', ('flow-test.png', open(file_path, 'rb'), 'image/png')),
			('agree_sheet', ('flow-test.png', open(file_path, 'rb'), 'image/png')),
			('family_before_info', ('blob', json_str.encode('utf-8'), 'application/json'))
		]
	)
	headers = {
	'Content-Type': m.content_type,
	"token":token
	}
	res = requests.post(res_url, data=m.to_string(), headers=headers)
	res_json = json.loads(res.text)
	if(len(res.text) > max_length):
		print(f'{now_time} {url} {res.text[:max_length]}......')
	else:
		print(f'{now_time} {url} {res_json}')
	return res_json


def opo_mix_upload_step9(url,payload,token):
	res_url = http_config['baseUrl'] + url
	json_str = json.dumps(payload)
	file_path = 'static/flow-test.png' 
	m = encoder.MultipartEncoder(
		fields=[
			('donate_zhiyuan', ('flow-test.png', open(file_path, 'rb'), 'image/png')),
			('brain_death_determination_sheet', ('flow-test.png', open(file_path, 'rb'), 'image/png')),
			('family_after_info', ('blob', json_str.encode('utf-8'), 'application/json'))
		]
	)
	headers = {
		'Content-Type': m.content_type,
		"token":token
	}
	res = requests.post(res_url, data=m.to_string(), headers=headers)
	res_json = json.loads(res.text)
	if(len(res.text) > max_length):
		print(f'{now_time} {url} {res.text[:max_length]}......')
	else:
		print(f'{now_time} {url} {res_json}')
	return res_json

def opo_mix_upload_step14(url,params,token):
	res_url = http_config['baseUrl'] + url

	file_path = 'static/flow-test.png' 

	operation_text = '1' 
	# 必须要有，传空会报错
	m = encoder.MultipartEncoder(
		fields=[
			('operation_record_file', ('flow-test.png', open(file_path, 'rb'), 'image/png')),
			 ('operation_text', ('',operation_text,"text/plain"))
		]
	)
	headers = {
		'Content-Type': m.content_type,
		"token":token
	}
	res = requests.post(res_url,params=params,data=m.to_string(),headers=headers)
	res_json = json.loads(res.text)
	if(len(res.text) > max_length):
		print(f'{now_time} {url} {res.text[:max_length]}......')
	else:
		print(f'{now_time} {url} {res_json}')
	return res_json



def opo_mix_upload_step19(url,params,token):
	res_url = http_config['baseUrl'] + url
	file_path = 'static/flow-test.png' 
	m = encoder.MultipartEncoder(
		fields=[
			('fileList', ('flow-test.png', open(file_path, 'rb'), 'image/png')),
			('abandon_text', ('', "脚本测试", 'text/plain'))
		]
	)
	headers = {
		'Content-Type': m.content_type,
		"token":token
	}
	res = requests.post(res_url, data=m.to_string(), params=params,headers=headers)
	res_json = json.loads(res.text)
	if(len(res.text) > max_length):
		print(f'{now_time} {url} {res.text[:max_length]}......')
	else:
		print(f'{now_time} {url} {res_json}')
	return res_json


def get_big_organ(token):
	res_json = opo_get("/utils/get_logical_existing_big_organ",{},token)
	if(res_json['code'] == 200):
		print("获取逻辑存在大器官成功")
		big_organ_id_list = []
		big_organ_list = []
		res_data = res_json['data']
		for big_organ in res_data:
			# print(big_organ['big_organ_id'])
			# print(big_organ['big_organ_id'])
			logical_existing = big_organ['logical_existing']
			if(logical_existing == 1):
				big_organ_id = big_organ['big_organ_id']
				big_organ_name = big_organ['organ_name']
				big_organ_id_list.append(big_organ_id)
				big_organ_list.append(big_organ_name)
		return big_organ_list,big_organ_id_list


def get_little_organ_id_list(token,big_organ_id_list):
	'''
	搭配大器官list使用
	目前是返回所有大器官对应的小器官
	'''
	res_json = opo_get("/utils/get_logical_existing_little_organ",{},token)
	# print(res_json)
	little_organ_id_list = []
	if(res_json['code'] == 200):
		little_organ_list = res_json['data']
		# 双肺与单肺互斥
		# 全肝与单肝互斥
		# 取一个就得了
		# 先遍历大器官

		for big_organ_id in big_organ_id_list:
			first = True
			for little_organ_info in little_organ_list:
				# print(little_organ_info)
				
				little_organ_big_id = little_organ_info['big_organ_id']
				# 小器官对应大器官id
				little_organ_id = little_organ_info['little_organ_id']
				if(big_organ_id == little_organ_big_id):
					if(first):
						little_organ_id_list.append(little_organ_id)
						first = False
			
	# print("小器官列表",little_organ_id_list)
	return little_organ_id_list


def get_subcase_big_organ_info_list(token,case_id):
	url = "/case_utils/get_big_organ_subcase"
	params = {"case_id":case_id}
	res_json = opo_get(url,params,token)
	# subcase_big_organ_list = res_json['data']
	return res_json['data']

def format_payload(payload):
	'''
	把payload中的字典/json对象转换为字符串
	payload : dict
	'''
	format_request_payload = {}
	for k,v in payload.items():
		if(type(v) == dict or type(v) == list):
			# print(k)
			data_json = json.dumps(v,ensure_ascii=False)
			format_request_payload[k] = data_json
		else:
			format_request_payload[k] = v
	return format_request_payload



def iso_timestamp_format(time_str):
    """
    输入格式为字符串 2025-03-12T12:19:12.000Z
    返回格式为字符串 2025-03-12 20:19:12
    """
    try:
        # 将输入的 ISO 8601 格式字符串解析为 datetime 对象
        dt = datetime.datetime.fromisoformat(time_str.replace('Z', '+00:00'))
        # 定义东八区的时区
        utc_8 = datetime.timezone(datetime.timedelta(hours=8))
        # 将时间转换为东八区时间
        dt_utc_8 = dt.astimezone(utc_8)
        # 将转换后的 datetime 对象按照目标格式进行格式化
        return dt_utc_8.strftime("%Y-%m-%d %H:%M:%S")
    except ValueError:
        print("输入的时间字符串格式不正确")
        return None

def generate_random_timestamp(start_time_str, end_time_str):
	"""
	输入格式为字符串 2025-03-11 12:00:00
	返回格式为字符串 "2025-03-011T06:00:00.000Z"
	"""
	# 将输入的字符串转换为 datetime 对象
	start_time = datetime.datetime.strptime(start_time_str, '%Y-%m-%d %H:%M:%S')
	end_time = datetime.datetime.strptime(end_time_str, '%Y-%m-%d %H:%M:%S')

	# 计算时间范围的总秒数
	total_seconds = (end_time - start_time).total_seconds()

	# 随机选择一个在总秒数范围内的秒数
	random_seconds = random.randint(0, int(total_seconds))

	# 生成随机的 datetime 对象
	random_time = start_time + datetime.timedelta(seconds=random_seconds)

	# 将 datetime 对象转换为指定格式的字符串
	timestamp_str = random_time.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'

	return timestamp_str


def convert_time_format(time_str):
	'''
	"2024-12-11T06:51:12.902Z"转换为"2024-12-04T14:30:03.000+00:00"
	'''
	try:
		# 将输入的字符串解析为 datetime 对象
		dt = datetime.datetime.fromisoformat(time_str.replace('Z', '+00:00'))
		# 将 datetime 对象转换为目标格式的字符串
		return dt.isoformat(timespec='milliseconds')
	except ValueError:
		print("输入的时间字符串格式不正确。")
		return None

def generate_random_id_number():
	# 随机选择地区码


	# 地区码列表
	area_codes = [
		'110000', '120000', '130000', '140000', '150000',
		'210000', '220000', '230000',
		'310000', '320000', '330000', '340000', '350000', '360000', '370000',
		'410000', '420000', '430000', '440000', '450000', '460000',
		'500000', '510000', '520000', '530000', '540000',
		'610000', '620000', '630000', '640000', '650000',
		'710000', '810000', '820000'
	]

	# 加权因子
	weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]

	# 校验码对应值
	check_code_list = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']

	area_code = random.choice(area_codes)

	start_date = datetime.date(1950, 1, 1)
	end_date = datetime.date(2000, 1, 1)
	random_date = start_date + datetime.timedelta(days=random.randint(0, (end_date - start_date).days))
	birth_date_str = random_date.strftime('%Y%m%d')

	# 随机生成顺序码
	sequence_code = str(random.randint(100, 999))

	# 组合前 17 位
	pre_17_digits = area_code + birth_date_str + sequence_code

	# 计算校验码
	total = 0
	for i in range(17):
		total += int(pre_17_digits[i]) * weights[i]
	check_code = check_code_list[total % 11]

	# 组合完整的身份证号码
	id_number = pre_17_digits + check_code

	return id_number

def analysis_id_number(id_number):
	# 提取出生日期
	birth_date_str = id_number[6:14]
	birth_date = datetime.datetime.strptime(birth_date_str, '%Y%m%d').date()

	# 计算年龄
	today = datetime.date.today()
	age = today.year - birth_date.year
	if today.month < birth_date.month or (today.month == birth_date.month and today.day < birth_date.day):
		age -= 1

	# 提取第 17 位数字来判断性别
	gender_digit = int(id_number[16])
	if gender_digit % 2 == 0:
		gender = '女'
	else:
		gender = '男'

	# 将出生日期、年龄和性别信息存储在字典中
	result = {
		'birth_date': str(birth_date),
		'age': age,
		'gender': gender,
		'nation':"汉族"
	}

	return result

